import React, {useEffect, useState} from "react";
import {Dropdown, Menu, Tabs} from "antd";
import {history, useIntl, useLocation} from "umi";
import {ProCard} from "@ant-design/pro-components";
import routes from "../../../config/routes";
import {BorderOuterOutlined, CloseOutlined, ColumnWidthOutlined, DeleteOutlined} from "@ant-design/icons";
import ProPage from "@/components/ProPage";

const {TabPane} = Tabs;
export const STORAGE_KEY = "multi_tabs"; // sessionStorage 记录 key

/**
 * 递归查找路由
 * @param routes 路由
 * @param path 路由路径
 */
const getBreadcrumb = (path, routes) => {
  let breadcrumb = [];
  const findRoute = (list, parentNames = []) => {
    for (const route of list) {
      const newParentNames = [...parentNames, route.name]; // 记录父级
      if (route.path === path) {
        breadcrumb = newParentNames;
        return route;
      }
      if (route.routes) {
        const currentRoute = findRoute(route.routes, newParentNames);
        if (currentRoute) {
          return currentRoute;
        }
      }
    }
  };
  const currentRoute = findRoute(routes);
  return {
    name: breadcrumb.join("."),
    route: currentRoute,
  };
};

const MultiTabs = ({children}) => {
  const location = useLocation();
  const [tabs, setTabs] = useState([]);
  const [targetTabKey, setTargetTabKey] = useState(null);
  const intl = useIntl();

  // 读取 sessionStorage 里的 tabs
  useEffect(() => {
    const storedTabs = sessionStorage.getItem(STORAGE_KEY);
    if (storedTabs) {
      setTabs(JSON.parse(storedTabs));
    } else {
      setTabs([{key: "/", title: "首页"}]);
    }
  }, []);

  // 监听路由变化，新增或切换标签页
  useEffect(() => {
    const {route, name} = getBreadcrumb(location.pathname, routes);
    const routeName = intl.formatMessage({
      id: `menu.${name}`,
    });

    const currentPath = location.pathname;
    const storedTabs = sessionStorage.getItem(STORAGE_KEY);
    let currentTabs = storedTabs ? JSON.parse(storedTabs) : [];

    if (!currentTabs?.some((tab) => tab.key === currentPath)) {
      currentTabs.push({key: currentPath, title: routeName});
      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(currentTabs));
    }
    setTabs(currentTabs);
  }, [location.pathname]);

  // 关闭标签页
  const removeTab = (targetKey) => {
    let newTabs = tabs.filter((tab) => tab.key !== targetKey);
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
    setTabs(newTabs);

    if (targetKey === location.pathname) {
      const lastTab = newTabs[newTabs.length - 1];
      history.push(lastTab?.key || "/");
    }
  };

  // 关闭所有标签页
  const closeAllTabs = () => {
    const newTabs = tabs.filter((tab) => tab.key === "/");
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
    setTabs(newTabs);
    history.push("/");
  };

  // 关闭其他标签页
  const closeOtherTabs = () => {
    const newTabs = tabs.filter((tab) => tab.key === targetTabKey || tab.key === "/");
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
    setTabs(newTabs);
  };

  // 关闭右侧标签页
  const closeRightTabs = () => {
    const targetIndex = tabs.findIndex((tab) => tab.key === targetTabKey);
    const newTabs = tabs.slice(0, targetIndex + 1);
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
    setTabs(newTabs);
  };

  // 右键菜单
  const menu = (
    <Menu>
      <Menu.Item
        icon={<CloseOutlined/>}
        disabled={tabs?.length === 1 || targetTabKey !== location.pathname}
        key="closeCurrent"
        onClick={() => removeTab(targetTabKey)}>
        关闭当前
      </Menu.Item>
      <Menu.Item
        icon={<DeleteOutlined/>}
        disabled={tabs?.length === 1} key="closeAll" onClick={closeAllTabs}>
        关闭所有
      </Menu.Item>
      <Menu.Item
        icon={<BorderOuterOutlined/>}
        disabled={tabs?.length === 1} key="closeOther" onClick={closeOtherTabs}>
        关闭其他
      </Menu.Item>
      <Menu.Item
        icon={<ColumnWidthOutlined/>}
        disabled={tabs?.length === 1} key="closeRight" onClick={closeRightTabs}>
        关闭右侧
      </Menu.Item>
    </Menu>
  );

  return (
    <ProPage>
      <ProCard
        bordered
        size={"small"}
        headerBordered
      >
        <Tabs
          type="editable-card"
          hideAdd
          size={"small"}
          activeKey={location.pathname}
          onChange={(key) => history.push(key)}
          onEdit={(targetKey, action) => action === "remove" && removeTab(targetKey)}
        >
          {tabs.map((tab) => (
            <TabPane
              tab={
                <Dropdown overlay={menu} trigger={["contextMenu"]}>
                  <div onContextMenu={(e) => setTargetTabKey(tab.key)}>
                    {tab.title}
                  </div>
                </Dropdown>
              }
              key={tab.key}
              closable={tab.key !== "/"}
            >
              {location.pathname === tab.key ? children : null}
            </TabPane>
          ))}
        </Tabs>
      </ProCard>
    </ProPage>
  );
};

export default MultiTabs;
